package cc.geguol.socket;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 作者：13687
 * 日期：2017/5/29
 * 项目：Socket
 * 描述：文件上传与接收
 */
public class UpLoadFile {
	// 这里是服务端
	public static void main(String[] args) throws IOException {
		ServerSocket ss = new ServerSocket(4560);
        new Thread(() -> {
	        try {
		        Thread.sleep(4000);//等服务端上线
		        uploadClient();
	        } catch (InterruptedException e) {
		        e.printStackTrace();
	        } catch (IOException e) {
		        e.printStackTrace();
	        }
        }).start();
		while (true){
			Socket sc= ss.accept();//连接对象

			// 从流中获取文件 写入磁盘
			FileOutputStream fileOutputStream = new FileOutputStream("hello.png");

			BufferedInputStream bufferedInputStream=new BufferedInputStream(sc.getInputStream());


			byte[] buff= new byte[1024];
			while ((bufferedInputStream.read(buff)!=-1)){
				fileOutputStream.write(buff,0,buff.length);//往文件中写
			}
			System.out.println("接收完成");
			fileOutputStream.close();
			bufferedInputStream.close();
		}
	}

	/**
	 * 没毛病 这就是基本的文件流的读取操作
	 * @throws IOException
	 */
	public static void uploadClient() throws IOException {
		Socket socket = new Socket(InetAddress.getLocalHost(),4560);

		File  file = new File("C:\\Users\\13687\\Pictures\\Saved Pictures","pretty.jpg");

		BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));

		OutputStream so = socket.getOutputStream();
		System.out.println("开始发送");

		// 从文件中读，，往网络中写
		byte[] buff = new byte[1024];
		while ((bufferedInputStream.read(buff)!=-1)){
			so.write(buff,0,buff.length);
		}
		socket.shutdownOutput();
		System.out.println("发送完成");
		bufferedInputStream.close();
		so.close();
		socket.close();

	}
}
